package com.niit.realtime.service;


import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
@Data
public class StatsService {

    private AtomicInteger validCount = new AtomicInteger(0);
    private AtomicInteger invalidCount = new AtomicInteger(0);
    private ConcurrentHashMap<String, ProductStats> productValidInvalidCounts = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, AtomicInteger> categoryCounts = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, ConcurrentHashMap<String, ProductStats>> categoryProductValidInvalidCounts = new ConcurrentHashMap<>();
    private final ReentrantLock lock = new ReentrantLock();

    @Data
    public static class ProductStats {
        private AtomicInteger valid = new AtomicInteger(0);
        private AtomicInteger invalid = new AtomicInteger(0);

        // 直接使用AtomicInteger的方法
    }

    public void processOrderValidInvalidCount(String isValid, int count) {
        if ("Y".equals(isValid)) {
            validCount.addAndGet(count);
        } else if ("N".equals(isValid)) {
            invalidCount.addAndGet(count);
        }
        log.info("Updated {} count: {}", isValid, count);
    }

    public void processProductOrderStats(String productName, String isValid, int count) {
        String validType = "Y".equals(isValid) ? "Valid" : "Invalid";
        ProductStats stats = productValidInvalidCounts.computeIfAbsent(productName, k -> new ProductStats());

        // 修复：直接操作AtomicInteger
        if ("Y".equals(isValid)) {
            stats.getValid().addAndGet(count);  // 这里getValid()返回AtomicInteger
        } else {
            stats.getInvalid().addAndGet(count); // 这里getInvalid()返回AtomicInteger
        }
        log.info("Updated {} {} count: {}", productName, validType, count);
    }

    public void processCategoryOrderCounts(String category, int count) {
        AtomicInteger categoryCount = categoryCounts.computeIfAbsent(category, k -> new AtomicInteger(0));
        categoryCount.addAndGet(count);
        log.info("Updated {} count: {}", category, count);
    }

    public void processCategoryProductOrderStats(String category, String productName, String isValid, int count) {
        ConcurrentHashMap<String, ProductStats> productMap =
                categoryProductValidInvalidCounts.computeIfAbsent(category, k -> new ConcurrentHashMap<>());

        ProductStats stats = productMap.computeIfAbsent(productName, k -> new ProductStats());

        // 修复：直接操作AtomicInteger
        if ("Y".equals(isValid)) {
            stats.getValid().addAndGet(count);
        } else {
            stats.getInvalid().addAndGet(count);
        }
        log.info("Updated {} {} {} count: {}", category, productName,
                "Y".equals(isValid) ? "Valid" : "Invalid", count);
    }

    public StatsData getAllStats() {
        lock.lock();
        try {
            StatsData stats = new StatsData();
            stats.setValidCount(validCount.get());
            stats.setInvalidCount(invalidCount.get());

            // 转换product stats
            ConcurrentHashMap<String, Map<String, Integer>> productStatsMap = new ConcurrentHashMap<>();
            productValidInvalidCounts.forEach((productName, statsObj) -> {
                Map<String, Integer> stat = new ConcurrentHashMap<>();
                stat.put("Valid", statsObj.getValid().get());  // 直接调用get()
                stat.put("Invalid", statsObj.getInvalid().get());
                productStatsMap.put(productName, stat);
            });
            stats.setProductValidInvalidCounts(productStatsMap);

            // 转换category counts
            ConcurrentHashMap<String, Integer> categoryMap = new ConcurrentHashMap<>();
            categoryCounts.forEach((category, count) -> {
                categoryMap.put(category, count.get());
            });
            stats.setCategoryCounts(categoryMap);

            // 转换category product stats
            ConcurrentHashMap<String, Map<String, Map<String, Integer>>> categoryProductMap = new ConcurrentHashMap<>();
            categoryProductValidInvalidCounts.forEach((category, productMap) -> {
                Map<String, Map<String, Integer>> innerMap = new ConcurrentHashMap<>();
                productMap.forEach((productName, productStats) -> {
                    Map<String, Integer> stat = new ConcurrentHashMap<>();
                    stat.put("Valid", productStats.getValid().get());
                    stat.put("Invalid", productStats.getInvalid().get());
                    innerMap.put(productName, stat);
                });
                categoryProductMap.put(category, innerMap);
            });
            stats.setCategoryProductValidInvalidCounts(categoryProductMap);

            log.info("Sending data to frontend: {}", stats);
            return stats;
        } finally {
            lock.unlock();
        }
    }

    @Data
    public static class StatsData {
        @JsonProperty("valid_count")
        private int validCount;
        @JsonProperty("invalid_count")
        private int invalidCount;

        @JsonProperty("product_valid_invalid_counts")
        private Map<String, Map<String, Integer>> productValidInvalidCounts;
        @JsonProperty("category_counts")
        private Map<String, Integer> categoryCounts;
        @JsonProperty("category_product_valid_invalid_counts")
        private Map<String, Map<String, Map<String, Integer>>> categoryProductValidInvalidCounts;
    }
}
